﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.UI.WebControls;
using GWEB.WebBase.Data;
using GWEB.WebBase.Entity;
using GWEB.WebBase.Utility;
using GWEB.WebFrame.Public;
using Newtonsoft.Json;

namespace GWEB.WebFrame.Contract
{
    public class ContractListController : PageInfoBase
    {        
        [ActionFilter(IsLogin = true)]
        public ActionResult Index(String id, String keyCode)
        {

            string sql = string.Format("select * from cu_sys_contract where LeagueId='1'");
            ViewBag.SetmealType = BasePage.bd.ExecuteTable(sql);
            sql = string.Format("select did,dname,typeid,helpcode from tb_sys_dictionary where typeid='D17'");
            ViewBag.Gift = BasePage.bd.ExecuteTable(sql);
            sql = string.Format("select did,dname,typeid from tb_sys_dictionary where typeid='D16'");
            ViewBag.AccountMode = BasePage.bd.ExecuteTable(sql);
            return Load("ContractList", "Contract/ContractList", id, keyCode);
        }
        [ActionFilter(IsLogin = true)]
        public JsonResult Data(String type, String id, String keyCode)
        {
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = @"select  cu_Customers.id ,'0' LinkCustId,CustName,ChildName,CustTel, cu_Customers.LinkName, cu_Customers.LinkRelation,LatelyReceId,Sex,cusImage,isnull(address,'未设置') address, 
                   isnull((select SUM(account) je from cu_Account where cid=cu_Customers.id  and FlowingType in ('00101001','00201001') and state=2),0) je,
isnull((select CreateUser.sshowname from  tb_sys_users CreateUser where CreateUser.iuserid  = cu_Customers.LatelyReceId),'未设置') AchievementName
                 from cu_Customers   where CustTel like '%" + keyCode+ @"%' and  cu_Customers.LeagueId='1' ";
            BasePage.bd.ColumnNameToLower = false;
            String str = JsonConvert.SerializeObject(BasePage.bd.ExecuteTable(sql));
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            return BasePage.Json(ResultData.OK(data));
        }

        protected override void FieldAddInit(DataRow data)
        {
            data["CreateId"] = BasePage.GetUserId(Session);
            data["LeagueId"] = 1;
            data["contracttype"] = "新签约";
            data["SetmealId"] = 0;
            data["GiveCourseNumber"] = 0;
            data["Gift1"] = "";
            data["method"] = "";
            data["Gift2"] = "";
            data["Gift3"] = "";
            data["state"] = 0;
            data["status"] =0;
            data["IsCharge"] = 0;
            base.FieldAddInit(data);
        }
        protected override SqlState SqlExecute(BaseData bd, String id, Dictionary<String, Object> data)
        {
            String ImageUrl = data["ImageUrl"].ToString();
            String ImageName = data["ImageName"].ToString();
            String CustId = data["CustId"].ToString();
            String LinkCustId = data["LinkCustId"].ToString();
            data.Remove("ImageUrl");
            data.Remove("ImageName");
            data.Remove("CustId");
            data.Remove("LinkCustId");
            //增加时取序列，修改是不取序列，否则会引发错误	
            string[] strImage = ImageUrl.Split(','); //字符串转数组
            string[] strImageName = ImageName.Split(','); //字符串转数组
            string[] strCustId = CustId.Split(','); //字符串转数组
            string[] strLinkId = LinkCustId.Split(','); //字符串转数组
            String[] sql = new String[4+strImage.Length+strCustId.Length];
            sql[0] = BaseData.MapToSql("cu_Contract", "id", id, data);
            int i = 0;
            for (i = 0; i < strImage.Length; i++)
                sql[i + 1] = "insert into  cu_Contract_Image(contractId,ImageUrl,ImageName) values([id],'" + strImage[i] + "','" + strImageName[i] + "')";
            int j = 0;
            for (j = 0; j < strCustId.Length; j++)
                sql[i + j + 1] = "insert into cu_Contract_Customer(contractId,CustId,LinkCustId) values([id],'" + strCustId[j] + "','" + strLinkId[j] + "')";
            string cid = "0";
            if (j > 0)
                cid = strCustId[0];
            string Remark ="合同:"+ data["ContractPrice"].ToString()+"实收:" + data["DisPrice"].ToString() + "已收:";
            decimal ssje = 0;

            string strSql = "select ADate,Account from cu_Account where cid={0}  and FlowingType in ('00101001','00201001') and state=2 ";
            DataTable dt = BasePage.bd.ExecuteTable(string.Format(strSql, cid));
            int djzt = 0;
            if (dt != null)
            {
                for (int rowsnumber = 0; rowsnumber < dt.Rows.Count; rowsnumber++)
                {
                    ssje += decimal.Parse(dt.Rows[rowsnumber]["Account"].ToString());
                    Remark += "日期：" + dt.Rows[rowsnumber]["ADate"].ToString() + "金额：" + dt.Rows[rowsnumber]["Account"].ToString();
                    djzt = 1;

                }
            }
            if (djzt == 0)
                Remark += "无";
            else
                Remark += "合计:" + ssje.ToString();
            string AccountSql = "insert into cu_Account(cid,AccountType,FlowingType,AccountMode,ADate,Account,Remark,ContractId,state,CreateId,CreateDate,AchievementId,LeagueId ) select '{0}' cid,'收入类' AccountType,'00101002' FlowingType,'{3}' method,ContractDate, DisPrice-{2} DisPrice,'{1}' remark,id,'0' state,CreateId,CreateDate,AchievementId,LeagueId from cu_Contract where id=[id]";
            sql[i + j + 1] = string.Format(AccountSql, cid, Remark, ssje.ToString(), data["method"].ToString());
            sql[i + j + 2] = string.Format("update cu_Account state='3' where  cid={0}  and FlowingType in ('00101001','00201001') and state=2 ", cid);
            sql[i + j + 3] = string.Format("update cu_Customers set CustState='6' where  id={0}", cid);
            bool t = bd.ExecuteSQL(sql, -1, "cu_Contract", "id", id);
            return t ? SqlState.True : SqlState.False;
        }
        [ActionFilter(IsLogin = false)]
        public JsonResult SetmealType(String type, String id, String keyCode)
        {
            PageInfo pg = isBrowse(type, id, keyCode);
            if (pg == null)
            {
                return BasePage.Json(ResultData.Error(WebMessage.NoBrowse));
            }
            String sql = "select *,case isclasshour when 1 then classhournumber else hournumber end number from cu_sys_contract where LeagueId='1' and id= " + keyCode;
            BasePage.bd.ColumnNameToLower = false;
            String str = JsonConvert.SerializeObject(BasePage.bd.ExecuteTable(sql));
            BasePage.bd.ColumnNameToLower = true;
            List<Dictionary<String, Object>> data = JsonConvert.DeserializeObject<List<Dictionary<String, Object>>>(str);
            return BasePage.Json(ResultData.OK(data));

        }
        [HttpPost]
        public ActionResult Upload(string DirName)
        {
            #region + 变量
            //文件大小（字节数）
            long fileSize = 0;
            //重命名的文件名称
            string tempName = "";
            //物理路径+重命名的文件名称
            string fileName = "";
            //文件扩展名
            string extname = "";
            //虚拟路径
            string dir = "/UpFile/"+DirName;
            string path = HostingEnvironment.MapPath(dir);

       
            //获取提交的文件
            var file = Request.Files[0];
            //反馈对象     

       

            string _response  = "{\"code\": 1,\"msg\": \"服务器故障\",\"data\": {\"src\": \"\"}}"; ;
            #endregion
            #region + 服务器本地文件上传处理
            try
            {
                if (file != null && !string.IsNullOrEmpty(file.FileName))
                {
                    dir = DateTime.Now.ToString("yyyy-MM-dd");
                    if (!Directory.Exists(path + dir))
                    {
                        Directory.CreateDirectory(path + dir);
                    }
                    extname = file.FileName.Substring(file.FileName.LastIndexOf('.'), (file.FileName.Length - file.FileName.LastIndexOf('.')));
                    tempName = Guid.NewGuid().ToString().Substring(0, 6) + extname;
                    fileName = path + dir + "/" + tempName;
                    fileSize += file.ContentLength;
                    using (FileStream fs = System.IO.File.Create(fileName))
                    {
                        file.InputStream.CopyTo(fs);
                        fs.Flush();
                    }
                   
                    _response= "{\"code\": 0,\"msg\": \"服务器本地上传成功\",\"data\": {\"src\": \"" + dir + "/" + tempName + "\"}}";
                  
                }
            }
            catch (Exception ex)
            {
                
                _response = "{\"code\": 2,\"msg\": \"服务器本地上传失败 / n" + "错误信息：" + ex.Message+ "\",\"data\": {\"src\": \"\"}}";
            }
            #endregion
            return Json(_response);
        }
    }
}